
# 读取文件内容
# file_path = "C:/Users/陈世玉/Desktop/Redis数据1(1).md"

import redis
import json
import re

# Redis 连接信
REDIS_HOST = "114.55.119.92"
REDIS_PORT = 6379
REDIS_DB = 0  # 选择数据库
REDIS_PREFIX = "chat"  # Key 前缀

# 连接 Redis
r = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)

# 读取文件内容
file_path = "C:/Users/陈世玉/Desktop/Redis数据1(1).md"

try:
    with open(file_path, "r", encoding="utf-8") as file:
        content = file.read()

    # **提取 JSON 代码块**
    json_blocks = re.findall(r'\{.*?\}', content, re.DOTALL)

    if not json_blocks:
        raise ValueError("未找到 JSON 数据")

    for i, json_content in enumerate(json_blocks):
        try:
            data = json.loads(json_content)  # 解析 JSON


            # **递归存入 Redis**
            def save_to_redis(namespace, data):
                if isinstance(data, dict):  # 处理字典
                    for key, value in data.items():
                        save_to_redis(f"{namespace}:{key}", value)
                elif isinstance(data, list):  # 处理数组
                    for index, item in enumerate(data):
                        save_to_redis(f"{namespace}:{index}", item)
                elif isinstance(data, bool):  # **处理布尔值**
                    r.set(namespace, "true" if data else "false")  # 方式1: 存为字符串
                    # r.set(namespace, 1 if data else 0)  # 方式2: 存为数值（可选）
                else:  # 处理普通值
                    r.set(namespace, data)


            save_to_redis(f"{REDIS_PREFIX}:{i}", data)
            print(f"成功存入 Redis: {REDIS_PREFIX}:{i}")

        except json.JSONDecodeError as e:
            print(f"JSON 解析失败 (第 {i + 1} 个 JSON): {e}")

except Exception as e:
    print(f"发生错误: {e}")



